package cn.conac.as.monitor.service;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import cn.conac.as.monitor.config.EmailConfig;
import cn.conac.as.monitor.entity.BdtVSystemInterfaceMonitorEntity;
import freemarker.core.ParseException;
import freemarker.template.MalformedTemplateNameException;
import freemarker.template.TemplateException;
import freemarker.template.TemplateNotFoundException;

/**
 * Created by liuwei on 2017-7-13.
 */
@Service
public class EmailServiceImpl implements EmailService {
	@Autowired
	private EmailConfig emailConfig;
	@Autowired
	private JavaMailSender mailSender;
	private static final String template = "mail/mail.ftl";

	@Autowired
	private FreeMarkerConfigurer freeMarkerConfigurer;

	public void sendTemplateMail(String email, BdtVSystemInterfaceMonitorEntity bdtVSystemInterfaceMonitorEntity) {
		try{
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("email", email);
		map.put("vSystemInterfaceMonitor", bdtVSystemInterfaceMonitorEntity);
			String text = getTextByTemplate(template, map);
			send(email, text);
		} catch (IOException | TemplateException e) {
			e.printStackTrace();
		} catch (MessagingException e) {
			e.printStackTrace();
		}catch(Exception e){
			e.printStackTrace();
		}
	}

	private String getTextByTemplate(String template, Map<String, Object> model) throws TemplateNotFoundException,
			MalformedTemplateNameException, ParseException, IOException, TemplateException {
		return FreeMarkerTemplateUtils
				.processTemplateIntoString(freeMarkerConfigurer.getConfiguration().getTemplate(template), model);
	}

	private String send(String email, String text) throws MessagingException, UnsupportedEncodingException {
		try{
		MimeMessage message = mailSender.createMimeMessage();
		MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");

		helper.setFrom(emailConfig.getEmailFrom());
		helper.setTo(email);
		helper.setSubject("测试邮件");
		helper.setText(text, true);
		mailSender.send(message);
		return text;
		}catch(Exception e){
			e.printStackTrace();
		}
		return null;
	}

}
